<template>
  <div class="production-progress">
    <el-card class="header-card">
      <div class="page-header">
        <div class="header-left">
          <h2>
            <el-icon><TrendCharts /></el-icon>
            生产进度跟踪
          </h2>
          <p>实时监控生产进度和工单执行情况</p>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出报表
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 进度概览 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
                <el-icon><DocumentCopy /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.totalOrders }}</div>
                <div class="stat-label">进行中的工单</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.onSchedule }}</div>
                <div class="stat-label">按期进行</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%)">
                <el-icon><WarningFilled /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.delayed }}</div>
                <div class="stat-label">进度延迟</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)">
                <el-icon><DataLine /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.avgProgress }}%</div>
                <div class="stat-label">平均进度</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="工单号">
          <el-input v-model="searchForm.workOrderNo" placeholder="请输入工单号" clearable />
        </el-form-item>
        <el-form-item label="车间">
          <el-select v-model="searchForm.workshop" placeholder="请选择车间" clearable>
            <el-option label="第一车间" value="1" />
            <el-option label="第二车间" value="2" />
            <el-option label="第三车间" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="进度状态">
          <el-select v-model="searchForm.progressStatus" placeholder="请选择" clearable>
            <el-option label="按期" value="onSchedule" />
            <el-option label="延迟" value="delayed" />
            <el-option label="提前" value="ahead" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" stripe border v-loading="loading">
        <el-table-column prop="workOrderNo" label="工单号" width="160" fixed />
        <el-table-column prop="productName" label="产品名称" width="180" />
        <el-table-column prop="workshopName" label="生产车间" width="120" />
        <el-table-column prop="currentProcess" label="当前工序" width="150" />
        <el-table-column prop="totalQty" label="订单数量" width="120" align="right">
          <template #default="{ row }">
            {{ row.totalQty }} {{ row.unit }}
          </template>
        </el-table-column>
        <el-table-column prop="completedQty" label="完成数量" width="120" align="right">
          <template #default="{ row }">
            <span :style="{ color: getQtyColor(row.completedQty, row.totalQty) }">
              {{ row.completedQty }} {{ row.unit }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="完成进度" width="180">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.progress" 
              :color="getProgressColor(row.progressStatus)"
              :format="() => `${row.progress}%`"
            />
          </template>
        </el-table-column>
        <el-table-column prop="progressStatus" label="进度状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.progressStatus)">
              {{ getStatusText(row.progressStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planEndDate" label="计划完成" width="120" />
        <el-table-column prop="estimatedEndDate" label="预计完成" width="120">
          <template #default="{ row }">
            <span :style="{ color: getDateColor(row.estimatedEndDate, row.planEndDate) }">
              {{ row.estimatedEndDate }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="daysLeft" label="剩余天数" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getDaysLeftType(row.daysLeft)">{{ row.daysLeft }} 天</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleViewDetail(row)">
              <el-icon><View /></el-icon> 详情
            </el-button>
            <el-button link type="success" size="small" @click="handleViewTimeline(row)">
              <el-icon><Clock /></el-icon> 时间线
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        class="pagination"
      />
    </el-card>

    <!-- 工序时间线对话框 -->
    <el-dialog v-model="timelineVisible" title="工序进度时间线" width="900px">
      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in timelineData"
          :key="index"
          :timestamp="item.timestamp"
          :color="item.status === 'completed' ? '#67c23a' : item.status === 'inProgress' ? '#409eff' : '#909399'"
        >
          <el-card>
            <div class="timeline-content">
              <div class="timeline-header">
                <h4>{{ item.processName }}</h4>
                <el-tag :type="item.status === 'completed' ? 'success' : item.status === 'inProgress' ? 'primary' : 'info'">
                  {{ getProcessStatusText(item.status) }}
                </el-tag>
              </div>
              <div class="timeline-body">
                <p><strong>工作中心：</strong>{{ item.workCenter }}</p>
                <p><strong>完成数量：</strong>{{ item.completedQty }} / {{ item.totalQty }}</p>
                <p><strong>操作员：</strong>{{ item.operator }}</p>
                <el-progress v-if="item.status === 'inProgress'" :percentage="item.progress" />
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  TrendCharts, Refresh, Download, Search, DocumentCopy,
  Timer, WarningFilled, DataLine, View, Clock
} from '@element-plus/icons-vue'

const searchForm = reactive({
  workOrderNo: '',
  workshop: '',
  progressStatus: ''
})

const statistics = reactive({
  totalOrders: 45,
  onSchedule: 32,
  delayed: 8,
  avgProgress: 68.5
})

const tableData = ref([])
const loading = ref(false)

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const timelineVisible = ref(false)
const timelineData = ref([])

const fetchData = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = [
      {
        id: '1',
        workOrderNo: 'WO202501001',
        productName: '产品A型号1',
        workshopName: '第一车间',
        currentProcess: '装配',
        totalQty: 500,
        completedQty: 325,
        progress: 65,
        unit: '件',
        progressStatus: 'onSchedule',
        planEndDate: '2025-01-20',
        estimatedEndDate: '2025-01-19',
        daysLeft: 8
      },
      {
        id: '2',
        workOrderNo: 'WO202501002',
        productName: '产品B型号2',
        workshopName: '第二车间',
        currentProcess: '加工',
        totalQty: 300,
        completedQty: 120,
        progress: 40,
        unit: '件',
        progressStatus: 'delayed',
        planEndDate: '2025-01-18',
        estimatedEndDate: '2025-01-22',
        daysLeft: 7
      },
      {
        id: '3',
        workOrderNo: 'WO202501003',
        productName: '产品C型号3',
        workshopName: '第三车间',
        currentProcess: '包装',
        totalQty: 800,
        completedQty: 700,
        progress: 87,
        unit: '件',
        progressStatus: 'ahead',
        planEndDate: '2025-01-25',
        estimatedEndDate: '2025-01-22',
        daysLeft: 11
      }
    ]
    pagination.total = 3
    loading.value = false
  }, 500)
}

const getQtyColor = (completed, total) => {
  const ratio = completed / total
  if (ratio >= 0.8) return '#67c23a'
  if (ratio >= 0.5) return '#e6a23c'
  return '#f56c6c'
}

const getProgressColor = (status) => {
  if (status === 'ahead') return '#67c23a'
  if (status === 'onSchedule') return '#409eff'
  return '#f56c6c'
}

const getStatusType = (status) => {
  const types = {
    onSchedule: '',
    delayed: 'danger',
    ahead: 'success'
  }
  return types[status] || ''
}

const getStatusText = (status) => {
  const texts = {
    onSchedule: '按期',
    delayed: '延迟',
    ahead: '提前'
  }
  return texts[status] || status
}

const getDateColor = (estimated, plan) => {
  if (estimated < plan) return '#67c23a'
  if (estimated === plan) return '#409eff'
  return '#f56c6c'
}

const getDaysLeftType = (days) => {
  if (days > 7) return 'success'
  if (days > 3) return 'warning'
  return 'danger'
}

const getProcessStatusText = (status) => {
  const texts = {
    completed: '已完成',
    inProgress: '进行中',
    pending: '未开始'
  }
  return texts[status] || status
}

const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    workOrderNo: '',
    workshop: '',
    progressStatus: ''
  })
  handleSearch()
}

const handleRefresh = () => {
  ElMessage.success('数据已刷新')
  fetchData()
}

const handleExport = () => {
  ElMessage.info('导出报表功能')
}

const handleSizeChange = (size) => {
  pagination.size = size
  fetchData()
}

const handlePageChange = (page) => {
  pagination.page = page
  fetchData()
}

const handleViewDetail = (row) => {
  ElMessage.info('查看详情：' + row.workOrderNo)
}

const handleViewTimeline = (row) => {
  timelineData.value = [
    {
      processName: '下料',
      timestamp: '2025-01-10 08:00:00',
      status: 'completed',
      workCenter: '下料车间',
      completedQty: 500,
      totalQty: 500,
      operator: '张三',
      progress: 100
    },
    {
      processName: '加工',
      timestamp: '2025-01-10 14:00:00',
      status: 'completed',
      workCenter: '加工车间',
      completedQty: 500,
      totalQty: 500,
      operator: '李四',
      progress: 100
    },
    {
      processName: '装配',
      timestamp: '2025-01-11 08:00:00',
      status: 'inProgress',
      workCenter: '装配车间',
      completedQty: 325,
      totalQty: 500,
      operator: '王五',
      progress: 65
    },
    {
      processName: '包装',
      timestamp: '',
      status: 'pending',
      workCenter: '包装车间',
      completedQty: 0,
      totalQty: 500,
      operator: '-',
      progress: 0
    }
  ]
  timelineVisible.value = true
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.production-progress {
  padding: 20px;

  .header-card {
    margin-bottom: 20px;
    
    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        h2 {
          display: flex;
          align-items: center;
          gap: 10px;
          margin: 0 0 10px 0;
          font-size: 24px;
          color: #303133;
        }

        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }

      .header-right {
        display: flex;
        gap: 10px;
      }
    }
  }

  .statistics-cards {
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        gap: 20px;

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 28px;
        }

        .stat-info {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .filter-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      justify-content: flex-end;
    }
  }

  .timeline-content {
    .timeline-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;

      h4 {
        margin: 0;
      }
    }

    .timeline-body {
      p {
        margin: 5px 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }
}
</style>

